package lt.vin.ht.server.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerException;

import lt.vin.ht.server.dao.SchemaDao;
import lt.vin.ht.server.dao.SrcDao;
import lt.vin.ht.shared.Src;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.xml.sax.SAXException;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class TransformerServlet extends HttpServlet  {

	/**
	 * 
	 */
	private static final long serialVersionUID = 979315324525203475L;

	@Inject
	private SrcDao srcDao;
	
	@Inject
	private SchemaDao schemaDao;
	
	@Inject
	private HtmlTransformer htmlTransformer;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sourceUrl = getSource(request);
		if (sourceUrl == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND, "No 'source' or 'sourceBase64' parameter found in request");
			return;
		}
				
		Src src = getSrcDao().getSrcForUrl(sourceUrl);
		if (src == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND, "No transformation info found for url '" + sourceUrl + "'");
			return;
		}
		
		String result;
		try {
			result = getHtmlTransformer().transform(
					sourceUrl, 
					src.getTransformation(), 
					getSchemaDao().getSchema(src.getSchemaId()));
		} catch (TransformerException e) {
			throw new ServletException(e);
		} catch (SAXException e) {
			throw new ServletException(e);
		}

		response.setContentType("text/xml");
		response.getWriter().write(result);
		response.setStatus(HttpServletResponse.SC_OK);
	}
	
	private String getSource(HttpServletRequest request) {
		if (StringUtils.isNotBlank(request.getParameter("source"))) {
			return request.getParameter("source");              
		} else if (StringUtils.isNotBlank(request.getParameter("sourceBase64"))) {
			return new String(Base64.decodeBase64(request.getParameter("sourceBase64").getBytes()));
		} else {
			return null;
		}
	}

	public SrcDao getSrcDao() {
		return srcDao;
	}

	public void setSrcDao(SrcDao srcDao) {
		this.srcDao = srcDao;
	}

	public HtmlTransformer getHtmlTransformer() {
		return htmlTransformer;
	}

	public void setHtmlTransformer(HtmlTransformer htmlTransformer) {
		this.htmlTransformer = htmlTransformer;
	}

	public SchemaDao getSchemaDao() {
		return schemaDao;
	}

	public void setSchemaDao(SchemaDao schemaDao) {
		this.schemaDao = schemaDao;
	}
}
